package cn.zifangsky.jvm.part2.threadlocal;

import java.util.HashMap;
import java.util.Map;

/**
 * 在线程中保存一些私有数据
 *
 * @author zifangsky
 * @date 2020/7/11
 * @since 1.0.0
 */
public class ThreadContext {
    /**
     * {@link User}的key
     */
    public static final String USER_KEY = ThreadContext.class.getName() + ":user";


    /**
     * 定义一个ThreadLocal
     */
    private static final ThreadLocal<Map<String, Object>> RESOURCES = new ThreadLocal<>();

    /**
     * 初始化
     */
    private static void initialize() {
        if (RESOURCES.get() == null) {
            RESOURCES.set(new HashMap<>());
        }
    }

    /**
     * 获取保存的所有数据
     *
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author zifangsky
     * @date 2020/2/13 17:48
     * @since 1.0.0
     */
    public static Map<String, Object> getResources() {
        Map<String, Object> result = new HashMap<>(16);

        Map<String, Object> resources = RESOURCES.get();
        if (resources != null && resources.size() > 0) {
            result.putAll(resources);
        }

        return result;
    }

    /**
     * 获取指定的值
     *
     * @param key key
     * @return java.lang.Object
     * @author zifangsky
     * @date 2020/2/13 17:52
     * @since 1.0.0
     */
    public static Object get(String key) {
        Map<String, Object> resources = RESOURCES.get();
        return resources != null ? resources.get(key) : null;
    }

    /**
     * 存放指定键值对
     *
     * @param key   key
     * @param value value
     * @author zifangsky
     * @date 2020/2/13 17:59
     * @since 1.0.0
     */
    public static void put(String key, Object value) {
        if (key == null) {
            throw new IllegalArgumentException("Parameter key cannot be empty.");
        }
        if (value == null) {
            remove(key);
        }

        initialize();
        RESOURCES.get().put(key, value);
    }

    /**
     * 移除指定键值对
     *
     * @author zifangsky
     * @date 2020/2/13 17:44
     * @since 1.0.0
     */
    public static void remove(String key) {
        Map<String, Object> resources = RESOURCES.get();
        if (resources != null) {
            resources.remove(key);
        }
    }

    /**
     * 移除所有
     *
     * @author zifangsky
     * @date 2020/2/13 17:44
     * @since 1.0.0
     */
    public static void remove() {
        RESOURCES.remove();
    }

    public static void setResources(Map<String, Object> newResources) {
        if (newResources != null && newResources.size() > 0) {
            initialize();
            RESOURCES.get().putAll(newResources);
        }
    }

}
